package cn.reinforce.util.juhe.function;

import cn.reinforce.util.http.HttpClientUtil;
import cn.reinforce.util.juhe.common.JuheConsts;
import cn.reinforce.util.juhe.exception.JuheException;
import cn.reinforce.util.juhe.model.IP;
import cn.reinforce.util.juhe.model.JuheResponse;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import org.apache.commons.lang3.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 幻幻Fate
 * @create 2019/12/23
 * @since
 */
public class IPUtil {



    public static JuheResponse ip2addr(String ip, String key) {
        if (StringUtils.isEmpty(ip)) {
            throw new JuheException("IP不能为空");
        }

        Pattern r = Pattern.compile(JuheConsts.IP_PATTERN);
        Matcher m = r.matcher(ip);

        if (!m.matches()) {
            throw new JuheException("IP格式不正确");
        }


        Gson gson = new GsonBuilder().create();

        String result = HttpClientUtil.get("http://apis.juhe.cn/ip/ipNew?ip=" + ip + "&key=" + key).getResult();
        JuheResponse response = gson.fromJson(result, JuheResponse.class);

        IP ip1 = gson.fromJson(gson.toJson(response.getResult()), IP.class);
        response.setIp(ip1);

        return response;
    }
}
